from utils import log, http_response
from utils import template
import random
from models.user import User

session = {}


def random_str():
    seed = 'abcdefghijk12345678abcdefghijklmn'
    s = ''
    for i in range(16):
        random_index = random.randint(0, len(seed) - 2)
        s += seed[random_index]
    return s


def current_user(request):
    session_id = request.cookies.get('user', '')
    user_id = int(session.get(session_id, '-1'))
    u = User.find_by(id=user_id)
    return u


def route_login(request):
    headers = {}
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_login():
            # session_id = random_str()
            # session[session_id] = u.username
            # headers['Set-Cookie'] = 'user={}'.format(session_id)
            user = User.find_by(username=u.username)
            session_id = random_str()
            session[session_id] = user.id
            headers['Set-Cookie'] = 'user={}'.format(session_id)
            log('headers response', headers)
            return redirect('/', headers)
    body = template('login.html')
    return http_response(body, headers=headers)


def redirect(location, headers=None):
    if headers is None:
        headers = {
            'Content-Type': 'text/html',
        }
    headers['Location'] = location
    # 302 状态码的含义, Location 的作用
    header = response_with_headers(headers, 302)
    r = header + '\r\n' + ''
    return r.encode(encoding='utf-8')


def response_with_headers(headers, status_code=200):
    """
    Content-Type: text/html
    Set-Cookie: user=gua
    """
    header = 'HTTP/1.1 {} VERY OK\r\n'.format(status_code)
    header += ''.join(['{}: {}\r\n'.format(k, v)
                       for k, v in headers.items()])
    return header


def route_register(request):
    if request.method == 'POST':
        form = request.form()
        # u = User.new(form)
        u = User(form)
        if u.validate_register():
            u.save()
            return redirect('/login')
        else:
            return redirect('/register')
    body = template('register.html')
    return http_response(body)


def route_admin_users(request):
    u = current_user(request)
    if u is not None and u.is_admin():
        us = User.all()
        body = template('admin_users.html', users=us)
        return http_response(body)
    else:
        return redirect('/login')


def route_admin_user_update(request):
    form = request.form()
    user_id = form.get('id', -1)
    new_password = form.get('password', '')
    u = User.find_by(id=user_id)
    if u is not None:
        u.password = new_password
        u.save()
    return redirect('/admin/users')


route_dict = {
    '/login': route_login,
    '/register': route_register,
    '/admin/users': route_admin_users,
    '/admin/users/update': route_admin_user_update,
}
